let url = "";
let timeOut: NodeJS.Timeout | undefined;
const onPopState: OnPopstateFun[] = [];
const lockNativeBack = {
  isLocked: false,
  /**
   * 锁定返回
   * @param timingUnLock 定时解锁返回
   * @returns
   */
  lock(timingUnLock?: number) {
    console.log("锁定");
    if (this.isLocked) return;
    this.isLocked = true;
    url = window.location.href;
    window.history.pushState(null, "", url);
    window.addEventListener("popstate", this.handlePopState);
    if (timingUnLock) this.timingUnLock(timingUnLock);
  },
  /**
   * 解锁返回
   * @returns
   */
  unLock() {
    this.cancelTimingUnLock();
    if (!this.isLocked) return;
    this.isLocked = false;
    console.log("解锁");
    window.removeEventListener("popstate", this.handlePopState);
    window.history.go(-1);
  },
  /**
   * 定时解锁返回
   * @param time 定时时间
   */
  timingUnLock(time: number) {
    this.cancelTimingUnLock();
    if (time > 0) timeOut = setTimeout(() => this.unLock(), time);
  },
  /**
   * 取消定时解锁返回
   */
  cancelTimingUnLock() {
    if (timeOut) {
      clearTimeout(timeOut);
      timeOut = undefined;
    }
  },
  handlePopState() {
    window.history.pushState(null, "", url);
    onPopState.forEach((f) => f());
  },
  /**订阅popstate */
  onPopstate(f: OnPopstateFun) {
    onPopState.push(f);
  },
  /**取消订阅popstate */
  unOnPopstate(f: OnPopstateFun) {
    for (const k in onPopState) {
      const i = Number(k);
      if (onPopState[i] === f) onPopState.splice(i, 1);
    }
  },
};
export default lockNativeBack;
export type OnPopstateFun = (...p: any[]) => any;
